import datetime

from sqlalchemy import text
from app.db.session import get_db
from config import Config
import logging

logger = logging.getLogger(__name__)


class RuleChecker:
    def __init__(self, base_db,origin_db,dest_db):
        self.db = base_db
        self.origin_db = origin_db
        self.dest_db = dest_db
    def _compare_values(self, actual, standard, operator):
        """
        比较实际值与标准值，支持数值和字符串比较

        参数:
            actual: 实际值 (可能为数值或字符串)
            standard: 标准值 (可能为数值或字符串)
            operator: 比较运算符 ('>', '<', '=', '>=', '<=', '!=', 'in', 'not in', 'contains')

        返回:
            bool: 比较结果
        """
        # 处理空值情况
        if actual is None or standard is None:
            if operator == '=':
                return actual == standard
            elif operator == '!=':
                return actual != standard
            return False

        # 尝试数值比较
        try:
            actual_num = float(actual)
            std_num = float(standard)
            # 数值比较
            if operator == '>':
                return actual_num > std_num
            elif operator == '<':
                return actual_num < std_num
            elif operator == '=':
                return actual_num == std_num
            elif operator == '>=':
                return actual_num >= std_num
            elif operator == '<=':
                return actual_num <= std_num
            elif operator == '!=':
                return actual_num != std_num
        except (ValueError, TypeError):
            # 无法转换为数值，进行字符串比较
            actual_str = str(actual).lower() if isinstance(actual, str) else str(actual)
            std_str = str(standard).lower() if isinstance(standard, str) else str(standard)

            # 字符串比较
            if operator == '=':
                return actual_str == std_str
            elif operator == '!=':
                return actual_str != std_str
            elif operator == 'contains' or operator == 'in':
                return std_str in actual_str
            elif operator == 'not in':
                return std_str not in actual_str
            elif operator == '>':
                return actual_str > std_str
            elif operator == '<':
                return actual_str < std_str
            elif operator == '>=':
                return actual_str >= std_str
            elif operator == '<=':
                return actual_str <= std_str

        # 默认返回 False
        return False

    def execute_query(self,sql,db,base_dict):
        try:

            result = db.execute(text(sql%(base_dict)))
            row = result.fetchone()
            if row:
                # 返回首行首列值
                return row[0]
            return None
        except Exception as e:
            logger.error(f"SQL执行失败: {e}\nSQL: {sql}")
            return None

    def check_rule(self, rule):

        # 基础变量
        base_dict = {
            "today": datetime.datetime.now().strftime("%Y-%m-%d"),
            "T-1": (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d"),
            "T-2": (datetime.datetime.now() - datetime.timedelta(days=2)).strftime("%Y-%m-%d"),
            "T-8": (datetime.datetime.now() - datetime.timedelta(days=8)).strftime("%Y-%m-%d"),
            "T-30": (datetime.datetime.now() - datetime.timedelta(days=30)).strftime("%Y-%m-%d"),
            "now": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "N-1": (datetime.datetime.now() - datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"),
            "N-2": (datetime.datetime.now() - datetime.timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),
            "N-3": (datetime.datetime.now() - datetime.timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S"),
            "N-8": (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),

            "H-1": (datetime.datetime.now() - datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"),
            "H-2": (datetime.datetime.now() - datetime.timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),
            "H-3": (datetime.datetime.now() - datetime.timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S"),
            "H-8": (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
            #10分钟前
            "M-10": (datetime.datetime.now() - datetime.timedelta(minutes=10)).strftime("%Y-%m-%d %H:%M:%S"),

        }
        # 执行检测SQL
        actual_value = self.execute_query(rule.query_sql,self.origin_db,base_dict)
        # 获取标准值
        if rule.standard_type == 'SQL':
            standard_value = self.execute_query(rule.standard_value,self.dest_db,base_dict)
        else:
            standard_value = rule.standard_value

        # 执行比较
        triggered = self._compare_values(
            actual_value,
            standard_value,
            rule.operator
        )

        return triggered, actual_value,standard_value,rule.operator,base_dict